﻿Imports System.ServiceModel
Imports System.IO
Imports System.Text

Public Class frmToken

    Private Sub btnGetToken_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetToken.Click
        Dim _random As Random = New Random()
       
        Dim transactionID As Long = _random.[Next]()
        Dim token = [String].Empty


        Try
            Using securitySrv = New SrvSecurity.SeguridadClient()
                Dim serviceToken = securitySrv.ObtenerToken(Utilerias.RFC, transactionID)
                Dim toHash = [String].Format("{0}|{1}", Utilerias.Integrator_ID, serviceToken)
                token = Security.Hash(toHash)
            End Using
            txtToken.Text = token
            Using archivoXML As New StreamWriter(Application.StartupPath + "\token.properties", False, Encoding.Default)
                archivoXML.Write(String.Format("tokenTransaction={0}", token))
            End Using
        Catch serviceFault As FaultException(Of SrvSecurity.FallaServicio)
            Using errorForm = New frmError(TranslateFault.ToServiceError(serviceFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch sessionFauld As FaultException(Of SrvSecurity.FallaSesion)
            Using errorForm = New frmError(TranslateFault.ToSessionError(sessionFauld.Detail))
                errorForm.ShowDialog()
            End Using
        Catch validationFault As FaultException(Of SrvInvoices.FallaValidacion)
            Using errorForm = New frmError(TranslateFault.ToValidationError(validationFault.Detail))
                errorForm.ShowDialog()
            End Using
        Catch ex As Exception
            ShowUnknownError(ex.Message)
        End Try

    End Sub
    Private Sub ShowSessionError(ByVal sessionError As Entity.SessionError)
        MessageBox.Show(String.Format("Status {0}: {1}", sessionError.Status.ToString(), sessionError.Description), "Ecodex UniTest")
    End Sub

    Private Sub ShowUnknownError(ByVal p1 As String)
        MessageBox.Show(String.Format("Error: {0}", p1), "Ecodex UniTest")
    End Sub
End Class